package com.yang;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Button;
import android.widget.ProgressBar;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private ProgressBar progressBar;

    private Button addBtn, pauseBtn, continueBtn, endBtn, toSecondBtn;

    private MyServiceConnection myServiceConnection;

    private AddOneService.MyBinder myBinder;

    private Timer timer;

    private TimerTask timerTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressBar = findViewById(R.id.progressBar);
        addBtn = findViewById(R.id.addBtn);
        pauseBtn = findViewById(R.id.pauseBtn);
        continueBtn = findViewById(R.id.continueBtn);
        endBtn = findViewById(R.id.endBtn);
        toSecondBtn = findViewById(R.id.toSecondBtn);
        Intent intent = new Intent(MainActivity.this, AddOneService.class);
        myServiceConnection = new MyServiceConnection();
        this.bindService(intent, myServiceConnection, BIND_AUTO_CREATE);
        addBtn.setOnClickListener(view -> {
            if (myBinder != null) {
                timer = new Timer();
                myBinder.startAddOne();
                timerTask = new TimerTask() {
                    @Override
                    public void run() {
                        if (myBinder != null) {
                            progressBar.setProgress(myBinder.getProgress());
                        }
                    }
                };
                timer.schedule(timerTask, 0, 100);
            }
        });

        pauseBtn.setOnClickListener(view -> {
            if (myBinder != null) {
                myBinder.pauseAddOne();
            }
        });

        continueBtn.setOnClickListener(view -> {
            if (myBinder != null) {
                myBinder.continueAddOne();
            }
        });

        endBtn.setOnClickListener(view -> {
            if (myBinder != null) {
                myBinder.endAddOne();
                unbindService(myServiceConnection);
                myBinder = null;
            }
        });

        toSecondBtn.setOnClickListener(view -> {
            Intent intent1 = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent1);
        });


    }

    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            myBinder = (AddOneService.MyBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    }
}